package org.xx.armory.http;

import org.xx.armory.commons.CalledBy;

import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import java.security.SecureRandom;

/**
 * SSLContext 相关的工具类。
 *
 * @author Haart
 * @see javax.net.ssl.SSLContext
 */
public final class SSLContextUtils {
    private static final SSLContext IGNORE_CERTIFICATE_CONTEXT = createIgnoreCertContext();

    /**
     * 禁止构造{@link SSLContextUtils}。
     */
    private SSLContextUtils() {
    }

    /**
     * 获取SSL上下文对象, 此上下文采用内部授信管理器。
     *
     * @return SSL上下文对象
     */
    @CalledBy
    public static SSLContext ignoreCert() {
        return IGNORE_CERTIFICATE_CONTEXT;
    }

    /**
     * 创建一个忽略证书的SSL上下文
     *
     * @return 忽略证书的SSL上下文
     * @throws IllegalStateException
     *         如果创建SSL上下文时出现错误。
     * @see IgnoreCertTrustManager
     */
    private static SSLContext createIgnoreCertContext() {
        try {
            final SSLContext sslContext = SSLContext.getInstance("TLS");

            sslContext.init(new KeyManager[0], new TrustManager[]{new IgnoreCertTrustManager()}, new SecureRandom());

            return sslContext;
        } catch (Exception ex) {
            throw new IllegalStateException("cannot create SSL CONTEXT", ex);
        }
    }
}
